package cn.aifeix.org.service.impl;

import cn.aifeix.basic.service.impl.BaseServiceImpl;
import cn.aifeix.org.domain.Department;
import cn.aifeix.org.mapper.DepartmentMapper;
import cn.aifeix.org.service.DepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements DepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;


    @Override
    public List<Department> deptTree() {
        List<Department> result = new ArrayList<>();
        List<Department> allDepts = departmentMapper.findAll();
        if (CollectionUtils.isEmpty(allDepts)){
            return result;
        }
        // stream
        Map<Long, Department> parentMap = allDepts.stream().collect(Collectors.toMap(Department::getId, e -> e));

        // 遍历
        for (Department dept : allDepts) {
            if (null == dept.getParentId()) {
                // 它就是最大的那个
                result.add(dept);
            } else {
                // 当前的这个dept 是个儿子
                Department parent = parentMap.get(dept.getParentId());
                if (null == parent){
                    break;
                }
                List<Department> children = parent.getChildren();
                children.add(dept);
            }
        }
        return result;
    }
}
